#!/bin/bash

# 服务器代码更新脚本
echo "🚀 开始更新服务器代码..."

# 设置变量
PROJECT_DIR="/root/clipboard-app"
BACKUP_DIR="/root/clipboard-backup"
DATE=$(date +%Y%m%d_%H%M%S)

# 创建备份目录
mkdir -p $BACKUP_DIR

# 进入项目目录
cd $PROJECT_DIR

# 备份当前代码
echo "📦 备份当前代码..."
tar -czf $BACKUP_DIR/clipboard_backup_$DATE.tar.gz .

# 备份数据库
if [ -f "clipboard.db" ]; then
    cp clipboard.db $BACKUP_DIR/clipboard_backup_$DATE.db
    echo "✅ 数据库已备份"
fi

# 备份配置文件
if [ -f ".env" ]; then
    cp .env $BACKUP_DIR/.env_backup_$DATE
    echo "✅ 配置文件已备份"
fi

# 拉取最新代码
echo "📥 拉取最新代码..."
git fetch origin
git reset --hard origin/main

# 检查是否有冲突
if [ $? -ne 0 ]; then
    echo "❌ Git拉取失败，尝试强制更新..."
    git reset --hard HEAD
    git pull origin main --force
fi

# 恢复配置文件
if [ -f "$BACKUP_DIR/.env_backup_$DATE" ]; then
    cp $BACKUP_DIR/.env_backup_$DATE .env
    echo "✅ 配置文件已恢复"
fi

# 恢复数据库
if [ -f "$BACKUP_DIR/clipboard_backup_$DATE.db" ]; then
    cp $BACKUP_DIR/clipboard_backup_$DATE.db clipboard.db
    echo "✅ 数据库已恢复"
fi

# 安装/更新依赖
echo "📦 更新依赖..."
pip install -r requirements.txt

# 停止旧应用
echo "🛑 停止旧应用..."
pkill -f "python.*app.py" || true
pkill -f "python.*start_tencent.py" || true

# 等待进程完全停止
sleep 3

# 启动新应用
echo "🚀 启动新应用..."
nohup python start_tencent.py > app.log 2>&1 &

# 等待应用启动
sleep 5

# 检查应用状态
if pgrep -f "python.*start_tencent.py" > /dev/null; then
    echo "✅ 应用启动成功"
    
    # 测试API
    echo "🧪 测试API..."
    sleep 2
    if curl -s http://localhost/api/collections > /dev/null; then
        echo "✅ API测试通过"
    else
        echo "⚠️  API测试失败，请检查日志"
    fi
else
    echo "❌ 应用启动失败，请检查日志"
    echo "📋 查看日志: tail -f app.log"
fi

echo "🎉 更新完成！"
echo "📋 查看应用日志: tail -f $PROJECT_DIR/app.log"
echo "📋 查看应用状态: ps aux | grep python"
